//import store from "@/store"
const { host } = require('../utils/host')
const getSign = require('../utils/getSign')
const { getConfig } = require('../config')


const request = (type = "get", url, data = {}, config = { headers: {}, baseurl: '', code: false }) => {
  if (!url) {
    return Promise.reject(new Error(`url Can not be empty`))
  }
  return new Promise((resolve, reject) => {
    let defaultErr = (res) => {console.log(res)}
    let rError = getConfig().requestError['error'] || defaultErr
    uni.request({
      url: `${config.baseurl || host()}${url}`,
      data: data,
      header: { ...getConfig().requestHeader, ...config.headers, ...getSign() },
      method: type,
      success: (res) => {
        let req = res.data;
        let unlogin = getConfig().requestError['410'] || defaultErr
        if (req.code === 0) {
          resolve(config.code ? req : req.data)
        } else if (req.code == 40001) {
          unlogin(req)
          reject(req)
          uni.removeStorageSync('openId')
          uni.removeStorageSync('token')
        } else {
          console.log(22)
          rError(req)
          reject(req)
        }
      },
      fail: (err) => {
        rError(err)
        reject(err)
      },
    })

  })

}



module.exports = { request };